import React, { Component } from 'react'
import {withRouter} from 'react-router-dom'
import {formateDate} from '../../utils/dateUtils'
import {reqWeather} from '../../api/index'
import memoryUser from '../../utils/memoryUtils'
import menuList from '../../config/menuConfig'
import storage from '../../utils/storageUtils'
import LinkButton from '../link-button'
import { Modal } from 'antd';
import './index.less'



class Header extends Component {
  
  props: any
  timer: any

  state = {
    currentTime: formateDate(Date.now()), // 当前时间字符串
    weather: '', // 天气文本
  }

  // 时间
  getTime = () => {
    this.timer = setInterval(() => {
      const currentTime = formateDate(Date.now())
      this.setState({currentTime})
    },1000)
  }

  // 天气
  getWeather = async () => {
    // 调用接口，获取异步数据
    const {weather} = await reqWeather('江西')
    // 改变状态
    this.setState({weather})
  }

  // 获取标题
  getTitle = () => {
    // 得到当前的请求路径
    const path = this.props.location.pathname
    let title
    // 遍历menuList
    menuList.forEach(item => {
      // 如果item的key值与path值一样，itme的title就是当前需要显示的title
      if (item.key === path){
        // 取出title
        title = item.title
      } else if (item.children) {
        // 所有子item中查找匹配项
        const zItem = item.children.find(zItem => path.indexOf(zItem.key)===0)
        // 如果有值，说明可以进行匹配
        if (zItem) {
          // 取出title
          title = zItem.title
        }
      }
    })
    return title
  }

  /**
   * 退出登录
   */
   loginOut = () => {
    Modal.confirm({
      title: '你确定要退出登录吗?',
      // content: '你确定要退出登录吗?',
      onOk:() => {
        console.log('确定')
        // 删除保存的user数据
        storage.removeUser()
        memoryUser.user = {}
        //  跳转到登录页面
        this.props.history.replace('/login')
      }
    })
  }

  /**
   * 第一次调用render()
   */
  componentDidMount() {
    this.getTime() //显示时间
    this.getWeather() // 显示天气
    this.getTitle() // 获取标题
  }
  /**
   * 在当前组件卸载之前
   */
  componentWillUnmount() {
    clearInterval(this.timer)
  }

  render() {
    // 取出{ currentTime, weather }
    const { currentTime, weather } = this.state
    // 取出username
    const username = memoryUser.user.username
    // 取出title
    const title = this.getTitle()
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎，{username}</span>
          <LinkButton onClick={this.loginOut}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span className="header-bottom-right-time">{currentTime}</span>
            <span>{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}

export default withRouter(Header)
